<?php

/**
 *
 * susan-webui - Susan Web-Frontend
 *
 * @link      https://github.com/susan/susan for the canonical source repository
 * @copyright Copyright (c) 2013-2020 Hechzh Property (http://www.susan.org/)
 * @license   GNU Affero General Public License (http://www.gnu.org/licenses/)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

$title = 'Jobs';
$this->headTitle($title);

?>

<ul class="nav nav-tabs">
   <li class="active"><a href="<?php echo $this->url('job', array('action'=>'index')); ?>"><?php echo $this->translate('Show'); ?></a></li>
   <li><a href="<?php echo $this->url('job', array('action'=>'actions')); ?>"><?php echo $this->translate('Actions'); ?></a></li>
   <li><a href="<?php echo $this->url('job', array('action'=>'run')); ?>"><?php echo $this->translate('Run'); ?></a></li>
</ul>

<br />

<?php if($this->acl_alert) : echo $this->ACLAlert($this->invalid_commands); elseif(!$this->acl_alert) : ?>

<div class="row">

<div class="col-md-12">

<div class="panel panel-default">

<div class="panel-heading">
   <h3 class="panel-title"><?php echo $this->translate('Job list'); ?></h3>
</div>

<div class="panel-body">

<div class="col-md-8"><input id="rangeslider" style="width: 100%;"></div>

<div class="job-table-toolbar" id="job-table-toolbar">
   <button class="btn btn-default" id="btn-clear-search-filters" title="<?php echo $this->translate("Clear search filters"); ?>">
      <span class="glyphicon glyphicon-trash"></span>
   </button>
</div>

<table
   class="table table-no-bordered table-hover"
   id="jobtable"
   data-toolbar=".job-table-toolbar"
   data-toolbar-align="right"
   data-filter-control="true">

<thead class="bg-primary">
   <th
      data-field="jobid"
      data-width="200"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Job ID"); ?>">
      <?php echo $this->translate("Job ID"); ?>
   </th>
   <th
      data-field="name"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Job name"); ?>">
      <?php echo $this->translate("Job name"); ?>
   </th>
   <th
      data-field="client"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Client"); ?>">
      <?php echo $this->translate("Client"); ?>
   </th>
   <th
      data-field="type"
      data-width="50"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Type"); ?>">
      <?php echo $this->translate("Type"); ?>
   </th>
   <th
      data-field="level"
      data-width="50"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Level"); ?>">
      <?php echo $this->translate("Level"); ?>
   </th>
   <th
      data-field="starttime"
      data-width="200"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Start"); ?>">
      <?php echo $this->translate("Start"); ?>
   </th>
   <th
      data-field="endtime"
      data-width="200"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("End"); ?>">
      <?php echo $this->translate("End"); ?>
   </th>
   <th
      data-field="jobfiles"
      data-width="100"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Files"); ?>">
      <?php echo $this->translate("Files"); ?>
   </th>
   <th
      data-field="jobbytes"
      data-width="100"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Bytes"); ?>">
      <?php echo $this->translate("Bytes"); ?>
   </th>
   <th
      data-field="joberrors"
      data-width="50"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Errors"); ?>">
      <?php echo $this->translate("Errors"); ?>
   </th>
   <th
      data-field="jobstatus"
      data-width="200"
      data-filter-control="input"
      data-filter-control-placeholder="<?php echo $this->translate("Status"); ?>">
      <?php echo $this->translate("Status"); ?>
   </th>
   <th
      data-width="100" ><?php echo $this->translate("Actions"); ?>
   </th>
</thead>

</table>

</div>
</div>
</div>
</div>

<!-- modal-001 start -->
<div id="modal-001" class="modal fade modal-001" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
   <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title" id="myModalLabel"><?php echo $this->translate("Failed to retrieve data from Susan director"); ?></h4>
      </div>
      <div class="modal-body">
   <p><?php echo $this->translate("Please try to reduce the amount of data to display."); ?></p>
   <p><?php echo $this->translate("Error message received from director:"); ?></p>
   <p class="text-danger"><?php echo $this->translate("Failed to send result as json. Maybe the result message is too long?"); ?></p>
      </div>
      <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo $this->translate("Close"); ?></button>
      </div>
    </div>
  </div>
</div>
<!-- modal-001 end -->

<!-- modal-002 start -->
<div id="modal-002" class="modal fade modal-002" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
         </button>
         <h4 class="modal-title" id="myModalLabel">Director message</h4>
      </div>
      <div class="modal-body">
         <p><?php echo str_replace(array("\n","\r"), "<br />", $this->result); ?></p>
      </div>
      <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo $this->translate("Close"); ?></button>
      </div>
    </div>
  </div>
</div>
<!-- modal-002 end -->

<?php
   echo $this->headScript()->prependFile($this->basePath() . '/js/custom-functions.js');
   echo $this->headLink()->prependStylesheet($this->basePath() . '/css/bootstrap-slider.min.css');
   echo $this->headLink()->prependStylesheet($this->basePath() . '/css/bootstrap-table-filter-control.min.css');
   echo $this->headLink()->prependStylesheet($this->basePath() . '/css/bootstrap-table.min.css');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-slider.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-formatter.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-filter-control.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-locale-all.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table-cookie.min.js');
   echo $this->headScript()->prependFile($this->basePath() . '/js/bootstrap-table.min.js');
?>

<script>

   var basePath = "<?php echo $this->basePath(); ?>";
   var result = '<?php echo str_replace(array("\n","\r"), "", $this->result); ?>';
   var displayRange = <?php echo $this->period; ?>;

   var rsLabel1 = "1 " + iJS._("day");
   var rsLabel2 = "3 " + iJS._("days");
   var rsLabel3 = "7 " + iJS._("days");
   var rsLabel4 = "2 " + iJS._("weeks");
   var rsLabel5 = "4 " + iJS._("weeks");
   var rsLabel6 = "3 " + iJS._("months");
   var rsLabel7 = "6 " + iJS._("months");
   var rsLabel8 = "1 " + iJS._("year");
   var rsLabel9 = "2 " + iJS._("years");
   var rsLabel10 = "5 " + iJS._("years");
   var rsLabel11 = "10 " + iJS._("years");

   // Table columns filter
   var jobid = null;
   var jobname = iJS._('<?php if($this->jobname !== "all") echo $this->jobname; ?>');
   var client = null;
   var jobtype = null;
   var joblevel = null;
   var jobstarttime = null;
   var jobendtime = null;
   var jobfiles = null;
   var jobbytes = null;
   var joberrors = null;
   var jobstatus = iJS._('<?php if($this->status !== "all") echo $this->status; ?>');

   var rangeslider = $("#rangeslider").bootstrapSlider({
      ticks: [1,3,7,14,31,90,180,365,730,1825,3650],
      ticks_labels: [rsLabel1, rsLabel2, rsLabel3, rsLabel4, rsLabel5, rsLabel6, rsLabel7, rsLabel8, rsLabel9, rsLabel10, rsLabel11],
      ticks_positions: [0,5,10,18,26,36,46,57,68,82,100],
      step: 1,
      lock_to_ticks: true,
      tooltip: "hide",
      handle: "round",
      value: <?php echo $this->period; ?>
   });

   function resetSearchFilters() {
      $('#jobtable').bootstrapTable('clearFilterControl');
      jobid = null;
      jobname = null;
      client = null;
      jobtype = null;
      joblevel = null;
      jobstarttime = null;
      jobendtime = null;
      jobfiles = null;
      jobbytes = null;
      joberrors = null;
      jobstatus = null;
   }

   function getSliderValue() {
      let range = document.getElementById("rangeslider");
      displayRange = range.value;
      $("#rangeValue").html(displayRange);
      refreshTableData();
   }

   function refreshTableData() {
      $('#spinner').fadeIn('slow');
      $('#jobtable').bootstrapTable('refreshOptions', {
         url: '<?php echo $this->url('job', array('action' => 'getData'), null) . '?data=jobs&period='; ?>' + displayRange,
      });
      $('.bootstrap-table-filter-control-jobid').val(jobid);
      $('.bootstrap-table-filter-control-name').val(jobname);
      $('.bootstrap-table-filter-control-client').val(client);
      $('.bootstrap-table-filter-control-type').val(jobtype);
      $('.bootstrap-table-filter-control-level').val(joblevel);
      $('.bootstrap-table-filter-control-starttime').val(jobstarttime);
      $('.bootstrap-table-filter-control-endtime').val(jobendtime);
      $('.bootstrap-table-filter-control-jobfiles').val(jobfiles);
      $('.bootstrap-table-filter-control-jobbytes').val(jobbytes);
      $('.bootstrap-table-filter-control-joberrors').val(joberrors);
      $('.bootstrap-table-filter-control-jobstatus').val(jobstatus);
      $('#spinner').fadeOut('slow');
   }

   function detailFormatter(index, row) {
      var html = [];
      html.push('<div class="container-fluid">');
      html.push('<table class="table table-bordered">');
      html.push('<tr>');
      html.push('<th><?php echo $this->translate("Fileset"); ?></th>');
      html.push('<td><a href="<?php echo $this->basePath() . '/fileset/details/'; ?>' + row.filesetid + '">' + row.fileset +'</a></td>');
      html.push('</tr>');
      html.push('<tr>');
      html.push('<th><?php echo $this->translate("Pool"); ?></th>');
      html.push('<td><a href="<?php echo $this->basePath() . '/pool/details/'; ?>' + row.poolname + '">' + row.poolname + '</a></td>');
      html.push('</tr>');
      html.push('<tr>');
      html.push('<th><?php echo $this->translate("Scheduled"); ?></th>');
      html.push('<td>' + row.schedtime + '</td>');
      html.push('</tr>');
      html.push('</table>');
      html.push('</div>');
      return html.join('');
   }

   function attachJobTable() {
      $('#jobtable').bootstrapTable({
         locale: '<?php echo str_replace('_','-', $_SESSION['susan']['locale']); ?>',
         cookie: <?php echo $_SESSION['susan']['dt_statesave']; ?>,
         cookieIdTable: 'dashboard_table_jobs_last_status',
         url: '<?php echo $this->url('job', array('action' => 'getData'), null) . '?data=jobs&period='; ?>' + displayRange,
         method: 'get',
         dataType: 'json',
         pagination : true,
         sidePagination: 'client',
         pageList: [ <?php echo $_SESSION['susan']['dt_lengthmenu']; ?> ],
         pageSize: <?php echo $_SESSION['susan']['dt_pagelength']; ?>,
         search: false,
         showPaginationSwitch: true,
         showColumns: true,
         showRefresh: true,
         sortName: 'jobid',
         sortOrder: 'desc',
         detailView: true,
         detailFormatter: 'detailFormatter',
         columns: [
            {
               field: 'jobid',
               sortable: true,
               formatter: function(value) {
                  return formatJobId(value, basePath);
               }
            },
            {
               field: 'name',
               sortable: true,
               formatter: function(value) {
                  return formatJobName(value, basePath, displayRange);
               }
            },
            {
               field: 'client',
               sortable: true,
               formatter: function(value) {
                  return formatClientName(value, basePath);
               }
            },
            {
               field: 'type',
               sortable: true,
               formatter: function(value) {
                  return formatJobType(value);
               }
            },
            {
               field: 'level',
               sortable: true,
               formatter: function(value) {
                  return formatJobLevel(value);
               }
            },
            {
               field: 'starttime',
               sortable: true
            },
            {
               field: 'endtime',
               sortable: true
            },
            {
               field: 'jobfiles',
               sortable: true,
            },
            {
               field: 'jobbytes',
               sortable: true,
               formatter: function(value) {
                  return formatBytes(value);
               }
            },
            {
               field: 'joberrors',
               sortable: true,
            },
            {
               field: 'jobstatus',
               sortable: true,
               formatter: function(value) {
                  return formatJobStatus(value);
               }
            },
            {
               field: 'action',
               formatter: function(value, row, index) {
                  return jobActionButtonsFormatter(value, row, index, basePath);
               }
            }
         ]
      });
   }

   $(document).ready(function() {

      setDtTextDomain('<?php echo $this->basePath() . '/js/locale'; ?>');
      setDtLocale('<?php echo $_SESSION['susan']['locale']; ?>');

      if(result.length > 0) {
         $("#modal-002").modal();
         window.history.pushState({}, document.title, window.location.pathname);
      }

      attachJobTable();

      // Set table filter input field values
      $('.bootstrap-table-filter-control-name').val(jobname);
      $('.bootstrap-table-filter-control-jobstatus').val(iJS._(jobstatus));

      $('#jobtable').on('load-error.bs.table', function(status, res) {
         $("#modal-001").modal();
      });

      $('#rangeslider').on('slideStop', getSliderValue);

      $('#btn-clear-search-filters').on('click', resetSearchFilters);
   });

   // Remember table filter input field values
   $(document).on('input', '.bootstrap-table-filter-control-jobid', function() {
      jobid = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-name', function() {
      jobname = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-client', function() {
      client = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-type', function() {
      jobtype = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-level', function() {
      joblevel = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-starttime', function() {
      jobstarttime = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-endtime', function() {
      jobendtime = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-jobfiles', function() {
      jobfiles = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-jobbytes', function() {
      jobbytes = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-joberrors', function() {
      joberrors = $(this).val();
   });

   $(document).on('input', '.bootstrap-table-filter-control-jobstatus', function() {
      jobstatus = $(this).val();
   });

   // Remember rangeslider value
   $(document).on('input', '#rangeslider', function() {
      displayRange = $(this).val();
   });

</script>

<?php endif; ?>
